const express = require("express");
const router = express.Router();
const request = require("request");
const path = require("path");
const fs = require("fs");

const TimeLineModel = require(path.resolve(
  __dirname,
  "../mongo_model/TimeLineModel"
));

//     res.header("Content-Type", "application/json")

router.get(
  "/testApi",
  (req, response, next) => {
    request(
      {
        url: "https://api.bilibili.com/pgc/web/timeline?types=1&before=6&after=6",
        port: 80,
        method: "GET",
        headers: {
          // Host : "www.bilibili.com",
          Cookie: `bid=k0KKZrbo7XM; ll="118124"; douban-fav-remind=1; _pk_id.100001.8cb4=4b3dd85a56799805.1689584866.; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1690859873%2C%22https%3A%2F%2Fwww.google.com%2F%22%5D; _pk_ses.100001.8cb4=1; __utma=30149280.56399573.1686458448.1689584786.1690859873.4; __utmc=30149280; __utmz=30149280.1690859873.4.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmt=1; __utmb=30149280.2.10.1690859873`,
          "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
        },
      },
      (err, res, body) => {
        if (err) {
          response.status(403).send({
            code: 0,
            data: null,
            message: "接口响应失败~~~",
          });
          return;
        }
        console.log(`STATUS: ${res.statusCode}`); //返回状态码
        res.setEncoding("utf8"); // 设置编码
        const newData = JSON.parse(body);
        if (newData.code != 0) {
          response.status(403).send({
            code: 0,
            data: null,
            message: "接口响应失败~~~",
          });
          return;
        }
        const resultData = newData.result;
        const newDateData = resultData.map((e) => ({
          date: e.date,
        }));
        response.resultData = newDateData; //过滤的时间数据
        response.wholeData = resultData; //完整数据
        next();

        return;

        TimeLineModel.find(
          {},
          {
            date: 1,
            _id: 0,
          }
        ).then((resp) => {
          const lastDate = resp[resp.length - 1];
          const date = lastDate.date;

          // 原本数据最后一条的时间 看新数据中是否有
          // 主要目标 间隔请求时间不是很长时间 就在最后一条时间
          // 在新的数据中 把当前数据之后插入到数据库
          let insertData = [];
          const findindex = newDateData.findIndex((item) => {
            return item.date == date;
          });
          if (findindex != -1) {
            insertData = resultData.splice(findindex + 1);
          } else {
            insertData = resultData;
          }

          console.log("完成的数据 >>>>>>>>>> ", insertData);

          // TimeLineModel.insertMany(insertData).then((res) => {
          //   if (res.length) {
          //     response.status(200).send({
          //       code: 1,
          //       data: {
          //         addLength: res.length,
          //         addData: res,
          //       },
          //       message: "添加成功~~~",
          //     });
          //   } else {
          //     response.status(200).send({
          //       code: 1,
          //       data: {
          //         addLength: res.length,
          //         addData: res,
          //       },
          //       message: "添加失败~~~",
          //     });
          //   }
          // });
        });
      }
    );
  },
  (req, response, next) => {
    const resultData = response.resultData;

    next();
  },
  (req, response) => {
    console.log(">>>>>>>>>>>>", response.resultData);

    response.status(200).send({
      code: 1,
      data: {},
      message: "响应成功~~~",
    });
  }
);

router.get("/getDB", (req, response) => {
  TimeLineModel.find({}).then((resp) => {
    // console.log(resp);
    response.status(200).send({
      code: 1,
      data: {
        DateData: {
          msg: "日期时间数据",
          data: resp.map((e) => ({
            date: e.date,
          })),
        },
        DBData: {
          msg: "数据库数据",
          data: resp,
        },
      },
      message: "获取数据成功~~~",
    });
  });
});

// 请求地址数据 写入json文件
router.get("/timeline", (req, response) => {

    
  request(
    {
      url: "https://api.bilibili.com/pgc/web/timeline?types=1&before=6&after=6",
      port: 80,
      method: "GET",
      headers: {
        Cookie: `bid=k0KKZrbo7XM; ll="118124"; douban-fav-remind=1; _pk_id.100001.8cb4=4b3dd85a56799805.1689584866.; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1690859873%2C%22https%3A%2F%2Fwww.google.com%2F%22%5D; _pk_ses.100001.8cb4=1; __utma=30149280.56399573.1686458448.1689584786.1690859873.4; __utmc=30149280; __utmz=30149280.1690859873.4.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmt=1; __utmb=30149280.2.10.1690859873`,
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
      },
    },
    async (err, res, body) => {
      if (err) {
        throw err;
      }
      console.log(`===========================STATUS: ${res.statusCode}`); //返回状态码
      // console.log(`HEADERS: ${JSON.stringify(res.headers, null, 4)}`); // 返回头部
      res.setEncoding("utf8"); // 设置编码
      const data = JSON.parse(body);
     
      if (res.statusCode == 200 && data.code == 0) {
        response.status(200).send({
          code: 1,
          data: data.result,
          message: "请求成功~~~",
        });
        const newTimeLinePath = path.resolve(
          __dirname,
          "../public/newtimeline.json"
        );
        await fs.writeFileSync(newTimeLinePath, ""); //尝试清空文件
        fs.writeFile(
          newTimeLinePath,
          JSON.stringify(data.result, null, 4),
          (err) => {
            if (err) {
              console.log("file wirte fail");
              return;
            }
            console.log("write file success");
          }
        );
      } else {
        response.status(405).send({
          code: 0,
          data: {},
          message: "响应失败",
        });
      }
    }
  );
});




 
module.exports = router;
